﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using MinistryStandardPlatformWeb.Models;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb.Controllers.RealTime;
using System.Threading;
using System.Threading.Tasks;
using System.Web.SessionState;


namespace MinistryStandardPlatformWeb.Controllers.Reports
{
    [MenuAuthorized("42")]
    //[SessionState(SessionStateBehavior.ReadOnly)]
    public class OverSpeedWarningController : AsyncController
    {
        //
        // GET: /OverSpeedWarning/
        private MSPGpsDataContext context = new MSPGpsDataContext();
        private MSPDataContext context1 = new MSPDataContext();

        MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
        //private bool parsePoiCompleted = false;


        public ActionResult Index(string startTime, string endTime)
        {
            ViewBag.StartTime = startTime;
            ViewBag.EndTime = endTime;
            return View();
        }

        public ActionResult Data(string startTime, string endTime, string vehicles, int pageIndex = 1)
        {
            if (Session["SearchData"] != null)
            {
                parsePagePoi(pageIndex, CommonDictionary.SmallerPageSize);
                return PartialView((Session["SearchData"] as IEnumerable<OverSpeedWarning>).ToPagedList(pageIndex, CommonDictionary.SmallerPageSize));
            }

            //得到要查询的车辆id的list
            List<string> vehiclesList = vehicles.Split(';').ToList();


            var warn = from w in context.GpsWarn
                       where vehiclesList.Contains(w.simId) &&
                       w.warntype == CommonDictionary.OverSpeedWarnType &&
                       string.Compare(w.warnstarttime, startTime) >= 0 &&
                       string.Compare(w.warnstarttime, endTime) <= 0
                       select new OverSpeedWarning()
                       {
                           VehicleId = w.vehicleId,
                           WarningTime = w.warnstarttime,
                           longitude = w.longitude,
                           latitude = w.latitude,
                           Speed = w.speed,
                           Sim=w.simId
                       };

            List<string> paramaters = new List<string>();
            for (int i = 0; i < vehiclesList.Count; i++)
            {
                paramaters.Add(vehiclesList[i].ToVarcharSqlParam());
            }
            paramaters.Add(CommonDictionary.OverSpeedWarnType.ToVarcharSqlParam());
            paramaters.Add(startTime.ToVarcharSqlParam());
            paramaters.Add(endTime.ToVarcharSqlParam());
            string warnStr = RealTimeGet.getReportFromGeoBase(CommonFunctions.GetLoginUser().UserId, CommonFunctions.GetSQL(warn, paramaters), startTime, endTime, "0");
            List<OverSpeedWarning> warnings = CommonFunctions.JsonStrToObject<List<OverSpeedWarning>>(warnStr);

            //查询车辆的list
            var vs = from v in context1.InfoVehicle
                     where vehiclesList.Contains(v.SIM)
                     select new OverSpeedWarning()
                     {
                         VehicleId = v.VehicleId,
                         ParentUnitName = v.InfoUnit.UNITNAME
                     };
            List<OverSpeedWarning> vehicleInfo = vs.ToList();

            //查询车辆的限定速度
            var speedlimit = from c in context1.CmdLogPara
                             where c.CmdName == CommonDictionary.SpeedLimitCmdName &&
                             vehiclesList.Contains(c.CmdSim)
                             group c by c.CmdSim into cg
                             let last = cg.Max(t => Convert.ToDateTime(t.CmdTime))
                             from r in cg
                             where Convert.ToDateTime(r.CmdTime) == last
                             select new OverSpeedWarning()
                             {
                                 Sim = r.CmdSim,
                                 SpeedLimit = r.CmdContent
                             };
            List<OverSpeedWarning> speedLimit = speedlimit.ToList();

            var overSpeedWarnings = from w in warnings
                                    join v in vehicleInfo
                                    on w.VehicleId equals v.VehicleId
                                    into wv
                                    join l in speedLimit
                                    on w.Sim equals l.Sim
                                    into wl
                                    from wvd in wv.DefaultIfEmpty()
                                    from wld in wl.DefaultIfEmpty()
                                    orderby w.VehicleId, w.WarningTime
                                    select new OverSpeedWarning()
                                    {
                                        VehicleId = w.VehicleId,
                                        ParentUnitName = wvd == null ? "" : wvd.ParentUnitName,
                                        WarningContent = "",
                                        WarningTime = w.WarningTime,
                                        longitude = w.longitude,
                                        latitude = w.latitude,
                                        Speed = w.Speed,
                                        POI = w.POI,
                                        SpeedLimit=wld==null?"":wld.SpeedLimit
                                    };
            Session["SearchData"] = overSpeedWarnings;

            ////开始地理解析（异步）
            //ParsePoi(Session);
            ////等待0.5s，尽量确保页面显示时第一页数据的地理位置已经解析出来
            //Thread.Sleep(5000);

            //解析当页数据的地理位置
            parsePagePoi(pageIndex, CommonDictionary.SmallerPageSize);

            PagedList<OverSpeedWarning> pl = (Session["SearchData"] as IEnumerable<OverSpeedWarning>).ToPagedList<OverSpeedWarning>(pageIndex, CommonDictionary.SmallerPageSize);
            //PagedList<MileageStatistics> r = new PagedList<MileageStatistics>(list, 1, 1);
            return PartialView(pl);
        }

        public Task<ActionResult> ExportData()
        {
            List<OverSpeedWarning> list;
            if (Session["SearchData"] != null)
            {
                list = (Session["SearchData"] as IEnumerable<OverSpeedWarning>).ToList();
            }
            else
            {
                ViewBag.Message = "数据已过期，请重新查询";
                return new Task<ActionResult>(() => { return View("ActionResult"); });
            }

            return Task.Factory.StartNew(() => startExport(list))
                 .ContinueWith(t =>
                 {
                     return t.Result;
             });
            
        }

        private ActionResult startExport(List<OverSpeedWarning> list)
        {
            ////等待地理解析完成
            //while (!parsePoiCompleted) { }

            for (int i = 0; i < list.Count; i++)
            {
                if (string.IsNullOrEmpty(list[i].POI))
                {
                    list[i].POI = geoHelper.GgpsTranslate2BaiduPoi(list[i].longitude.ToString(), list[i].latitude.ToString());
                }
            }

            //Session["SearchData"] = list;
            CommonController controller = new CommonController();
            Dictionary<string, string> title = new Dictionary<string, string>();
            title.Add("VehicleId", "车牌号");
            title.Add("ParentUnitName", "所属单位");
            title.Add("WarningTime", "报警时间");
            title.Add("Speed", "行驶速度（km/h）");
            title.Add("POI", "位置");
            string fileName = "超速报警统计";
            return controller.ListToExcel<OverSpeedWarning>(list, title, fileName, Server);
        }

        private void parsePagePoi(int pageIndex, int pageSize)
        {
            List<OverSpeedWarning> list = (Session["SearchData"] as IEnumerable<OverSpeedWarning>).ToList();
            int start = (pageIndex - 1) * pageSize;
            int end = pageIndex * pageSize - 1;
            for (int i = start; i <= end && i < list.Count; i++)
            {
                if (string.IsNullOrEmpty(list[i].POI))
                {
                    list[i].POI = geoHelper.GgpsTranslate2BaiduPoi(list[i].longitude.ToString(), list[i].latitude.ToString());
                }
            }

            Session["SearchData"] = list;
        }

        //public Task<bool> ParsePoi(HttpSessionStateBase session)
        //{
        //    return Task.Factory.StartNew(() => startParsing(session))
        //        .ContinueWith(t =>
        //        {
        //            parsePoiCompleted = true;
        //            return true;
        //        });
        //}

        //private void startParsing(HttpSessionStateBase session)
        //{
        //    List<OverSpeedWarning> list = (session["SearchData"] as IEnumerable<OverSpeedWarning>).ToList();
        //    MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
        //    for (int i = 0; i < list.Count;i++ )
        //    {
        //        list[i].POI = geoHelper.GgpsTranslate2BaiduPoi(list[i].longitude.ToString(), list[i].latitude.ToString());
        //        //每解析一页数据，要重写session
        //        if ((i + 1) % CommonDictionary.SmallerPageSize == 0)
        //        {
        //            session["SearchData"] = list;
        //        }
        //    }
        //    session["SearchData"] = list;
        //}
    }
}
